//
//  VerificationHelper.m
//  GLGW_Shoping
//
//  Created by whx on 2018/12/7.
//  Copyright © 2018年 yang. All rights reserved.
//

#import "VerificationHelper.h"

@implementation VerificationHelper

/**
 *  重新获取验证码的方法
 *
 *  @param sec             间隔的秒数
 *  @param completionBlock 间隔描述完成
 *  @param isRunBlock      正在倒计时
 */
+ (void)timerCountDown:(int)sec completionBlock:(void (^)())completionBlock isRunBlock:(void (^)(NSString *countDownSec))isRunBlock
{
    __block int timeout = sec; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //没秒执行
    dispatch_source_set_event_handler(_timer, ^{
        
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
#if !OS_OBJECT_USE_OBJC
            dispatch_release(_timer);
#endif
            dispatch_async(dispatch_get_main_queue(), ^{
                completionBlock();
            });
        } else {
            NSString *strTime = [NSString stringWithFormat:@"%.2d秒后重发",timeout];
            dispatch_async(dispatch_get_main_queue(), ^{
                isRunBlock(strTime);
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

+ (NSString *)getDataFormat:(NSString *)dataStr
{
    //获得服务器传回来的时间
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    [dateFormatter setDateFormat:@"EEEE HH:mm"];
    NSDate * scoreLogDate = [NSDate dateWithTimeIntervalSince1970:([dataStr doubleValue]/1000)];
    
    //带星期格式的时间
    NSString * scoreLogDateStr = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:scoreLogDate]];
    //获得当前时间
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
    
    //服务器的时间和当前时间对比
    NSCalendar * calendae = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents * week = [calendae components:NSCalendarUnitWeekdayOrdinal fromDate:localeDate toDate:scoreLogDate options:0];
    DLog(@"%ld",[week weekdayOrdinal]);
    if ([week weekdayOrdinal] == 0) {
        return scoreLogDateStr;
    } else {
        //带月日格式的时间
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
        [dateFormatter setDateFormat:@"M月d日 HH:mm"];
        NSDate * scoreLogDate = [NSDate dateWithTimeIntervalSince1970:([dataStr doubleValue]/1000)];
        NSString * scoreLogDateStr = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:scoreLogDate]];
        return scoreLogDateStr;
    }
}

@end
